package logic

import (
	"baidu/models/cache"
	"baidu/pkg"
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"baidu/baidurpc/baidurpc"
	"baidu/baidurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信验证码
func (l *SendSmsLogic) SendSms(in *baidurpc.SendSmsRequest) (*baidurpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	cmd := cache.Rdb.Get(l.ctx, in.Mobile)
	if cmd.Val() >= "1" {
		return nil, fmt.Errorf("一分钟只能发送一次")
	}

	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}

	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}

	cache.Rdb.Set(l.ctx, "sendSms"+in.Mobile, code, time.Minute*2)

	cache.Rdb.Incr(l.ctx, in.Mobile)
	cache.Rdb.Expire(l.ctx, in.Mobile, time.Minute*2)

	return &baidurpc.SendSmsResponse{}, nil
}
